<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j con-box user-home user-center">
    <!-- 账户信息 -->
    <div class="my-info">
      <div class="info-box">
        <div class="portrait-box">
          <div class="portrait">
            <img
              :src="hadAvatar?checkFileUrl(userAvatar):defaultAvatar"
              alt
            >
          </div>
          <div
            class="edit"
            @click="uploadPic()"
          >
            {{ $t('userIndex.editProfile') }}
          </div>
        </div>
        <div class="name-box">
          <div class="name">
            <div class="text">
              {{ nickName }}
            </div>
            <div
              v-if="memberInfo.levelType === 1"
              class="vip"
            >
              <img
                src="../../../assets/images/vip.png"
                alt=""
              >
            </div>
          </div>
          <div class="level-box">
            <div class="text">
              {{ $t('userIndex.level') }}：
            </div>
            <div>
              {{ userLevel.levelName }}
            </div>
          </div>
          <div class="level-box">
            <div class="text">
              {{ $t('userIndex.balance') }}：
            </div>
            <div
              class="to-balance"
              @click="toBalance()"
            >
              {{ currentBalance }}{{ $t('myBalance.yuan') }}
            </div>
          </div>
          <div class="level-box">
            <div class="text">
              {{ $t('userIndex.growthValue') }}：
            </div>
            <div
              v-if="memberInfo.nextGrowth"
              class="number"
            >
              {{ memberInfo.growth }}<span class="text">/{{ memberInfo.nextGrowth }}</span>
            </div>
            <div
              v-if="!memberInfo.nextGrowth"
              class="number"
            >
              {{ memberInfo.growth }}
            </div>
          </div>
        </div>
      </div>
      <div class="order-tab">
        <div
          class="item"
          @click="toOrderList(1)"
        >
          <div class="img unpaid" />
          <div class="text">
            {{ $t('obligation') }}
            <span class="number">{{ orderCountData.unPay }}</span>
          </div>
        </div>
        <div
          class="item"
          @click="toOrderList(2)"
        >
          <div class="img no-shipped" />
          <div class="text">
            {{ $t('pendingDelivery') }}
            <span class="number">{{ orderCountData.payed }}</span>
          </div>
        </div>
        <div
          class="item"
          @click="toOrderList(3)"
        >
          <div class="img shipped" />
          <div class="text">
            {{ $t('shipped') }}
            <span class="number">{{ orderCountData.consignment }}</span>
          </div>
        </div>
        <div
          class="item"
          @click="toOrderList(5)"
        >
          <div class="img no-reviewed" />
          <div class="text">
            {{ $t('completed') }}
            <span class="number">{{ orderCountData.success }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- /账户信息 -->
    <div
      :class="['buy-member',$t('language') === 'en'?'en':'']"
      @click="buyMember"
    >
      <div
        class="text"
        :style="{marginLeft: $t('language') ==='en'?'297px':''}"
      >
        <div class="big">
          {{ $t('userIndex.privileges') }}
        </div>
        <div
          class="small"
        >
          {{ $t('userIndex.openMembership') }}￥{{ memberPrice.needAmount }}/{{ ['',$t('dayRi'),$t('week'),$t('month'),$t('season'),$t('year')][memberPrice.termType] }}{{ $t('userIndex.valueOffer') }}
        </div>
      </div>
      <div
        class="btn"
        :style="{marginLeft: $t('language') ==='en'?'10px':''}"
      >
        {{ $t('userIndex.openNow') }}
      </div>
    </div>
    <!-- 我的订单 -->
    <div class="order-list">
      <div class="order-head">
        <span class="text">{{ $t('userIndex.myOrders') }}</span>
        <router-link
          :to="{path:'/user-center/uc-order',query:{status:0}}"
          class="all"
        >
          {{ $t('userIndex.viewAllOrders') }}
        </router-link>
      </div>
      <div
        v-if="orderList.length"
        class="order-table"
      >
        <table
          class="box"
        >
          <tbody>
            <tr
              v-for="(order,index) in orderList"
              :key="index"
              class="box-tr"
            >
              <td v-if="order.orderItemDtos.length === 1">
                <div class="goods-info">
                  <router-link
                    :to="{
                      path: '/detail',
                      query: order.orderType===3? { prodId: order.orderItemDtos[0].prodId, scoreFee: order.orderItemDtos[0].useScore } : { prodId: order.orderItemDtos[0].prodId }
                    }"
                    :target="order.orderType === 3?'':'_blank'"
                    class="img"
                  >
                    <img-show :src="order.orderItemDtos[0].pic" />
                  </router-link>
                  <div class="name-sku">
                    <router-link
                      :to="{
                        path: '/detail',
                        query: order.orderType===3? { prodId: order.orderItemDtos[0].prodId, scoreFee: order.orderItemDtos[0].useScore } : { prodId: order.orderItemDtos[0].prodId }
                      }"
                      :target="order.orderType === 3?'':'_blank'"
                      class="name"
                    >
                      {{ order.orderItemDtos[0].prodName }}
                    </router-link>
                    <span class="sku">{{ order.orderItemDtos[0].skuName }}</span>
                  </div>
                </div>
              </td>
              <td v-else>
                <div :class="['goods-info multi-good-info', order.orderItemDtos.length < 8 ? 'hide-scrollbar': '']">
                  <span
                    v-for="(orderItem, orderItemIndex) in order.orderItemDtos"
                    :key="orderItemIndex"
                  >
                    <router-link
                      :to="{
                        path: '/detail',
                        query: order.orderType===3? { prodId: order.orderItemDtos[orderItemIndex].prodId, scoreFee: order.orderItemDtos[orderItemIndex].useScore } : { prodId: order.orderItemDtos[orderItemIndex].prodId }
                      }"
                      :target="order.orderType === 3?'':'_blank'"
                      class="img"
                    >
                      <img-show
                        :src="orderItem.pic"
                        :img-alt="orderItem.spuName"
                      />
                      <div class="nums-con">x{{ orderItem.prodCount }}</div>
                    </router-link>
                  </span>
                </div>
              </td>
              <td
                class="br"
                width="117"
              >
                <div class="goods-number">
                  {{ $t('total') }} {{ order.totalCounts }} {{ $t('items') }}
                </div>
              </td>
              <td
                class="br"
                width="117"
              >
                <div class="amount">
                  <span
                    class="price"
                  >￥{{ parsePrice(order.actualTotal)[0] }}.{{ parsePrice(order.actualTotal)[1] }}</span>
                </div>
              </td>
              <td
                class="br"
                width="117"
              >
                <div class="status">
                  <div
                    class="text no-finish"
                  >
                    {{ ['',$t('obligation'),$t('pendingDelivery'),$t('pendingReceipt'),$t('pendinEvaluation'),$t('completed'),$t('canceled'),$t('grouping')][order.status] }}
                  </div>
                </div>
              </td>
              <td width="117">
                <div class="action">
                  <a
                    href="javascript:void(0)"
                    class="action-a"
                    @click="toOrderDetail(order.orderNumber)"
                  >{{ $t('userIndex.viewOrders') }}</a>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 空列表提示 -->
      <div
        v-if="!orderList.length"
        class="order-table"
      >
        <table
          cellspacing="0"
          cellpadding="0"
          class="box"
        >
          <tr class="box-tr">
            <empty-all-tips
              v-if="isEmpty"
              :text="$t('userIndex.noRelatedOrders')"
              :back="$t('userIndex.goShopping')"
              :src-type="1"
            />
          </tr>
        </table>
      </div>
      <!-- /空列表提示 -->
    </div>
    <!-- /我的订单 -->
  </div>
</template>

<script setup>
import Cookie from 'vue-cookies'
import buyerImg from '@/assets/images/buyer-img.png'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const defaultAvatar = ref(buyerImg)

const nickName = ref('')
const userAvatar = ref('')
const hadAvatar = ref(false)
onMounted(() => {
  // 修改用户信息后刷新页面
  if (location.href.indexOf('#reloaded') === -1 && route.query.refresh) {
    location.href = location.href + '#reloaded'
    location.reload()
  }
  // 设置网页标题
  document.title = $t('userIndex.personalCenter')
  getUserLevel()
  getMemberPrice()
  getUserInfo()
  getOrderList()
  getBalanceInfo()
  nickName.value = userStore.nickName
  userAvatar.value = userStore.userAvatar

  hadAvatar.value = !!userAvatar.value
})

const memberInfo = ref({}) // 会员信息
const userLevel = ref({}) // 会员等级
// 获取会员信息
const getUserLevel = () => {
  http.get('/p/score/scoreLevel/page?levelType=' + 0).then(({ data }) => {
    memberInfo.value = data
    getVipInternationalization(data.userLevel)
    userLevel.value = data.userLevel
  })
}

const memberPrice = ref({}) //  付费会员价
// 获取付费会员价格
const getMemberPrice = () => {
  http.get('/p/score/scoreLevel/minAmountLevel').then(({ data }) => {
    memberPrice.value = data
  })
}

// 去购买会员
const buyMember = () => {
  router.push({ path: '/member-center/buy-member' })
}

const orderCountData = ref({}) // 订单详情数据
/**
 * 获取订单数量
 */
const getUserInfo = () => {
  http.get('/p/user/centerInfo').then(({ data }) => {
    orderCountData.value = data.orderCountData
  })
}

const currentBalance = ref({}) // 余额信息
// 获取余额信息
const getBalanceInfo = () => {
  http.get('/p/userBalance/getBalanceInfo').then(({ data }) => {
    currentBalance.value = data
  })
}

const isEmpty = ref(false)
const orderList = ref([])
/**
 * 获取订单列表
 */
const getOrderList = () => {
  isEmpty.value = false
  const params = {
    current: 1,
    size: 10,
    status: 0
  }
  http.get('/p/myOrder/myOrder', { params }).then(({ data }) => {
    data.records.forEach(el => {
      el.totalCounts = 0
      el.orderItemDtos.forEach(prodItem => {
        el.totalCounts += prodItem.prodCount
      })
    })
    orderList.value = data.records
    isEmpty.value = !orderList.value.length
  })
}

/**
 * 跳转订单详情
 */
const toOrderDetail = (orderNumber) => {
  router.push({ path: '/order-detail', query: { orderNumber } })
}

/**
 * 跳转订单列表
 */
const toOrderList = (status) => {
  router.push({ path: '/user-center/uc-order', query: { status } })
}

/**
 * 跳转到账户信息
 */
const uploadPic = () => {
  router.push({ path: '/user-center/uc-account' })
}

// 去我的余额
const toBalance = () => {
  router.push({ path: '/user-center/uc-balance' })
}

/**
 * 价格处理
 */
const parsePrice = (value) => {
  let val = Number(value)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，并以小数点为切割点将val转化为数组
  return val.toFixed(2).split('.')
}

// 国际化
const getVipInternationalization = (data) => {
  if (!data) return
  const lang = Cookie.get('bbcLanguage') || 'zh_CN'
  let levelNameCn, levelNameEn
  if (!data.userLevelLangList) return
  data.userLevelLangList.forEach(val => {
    if (val.lang === 0) {
      levelNameCn = val.levelName
    }
    if (val.lang === 1) {
      levelNameEn = val.levelName
    }
  })
  data.levelName = lang === 'zh_CN' ? levelNameCn : levelNameEn || levelNameCn
}

</script>

<style lang="scss" scoped>
@use "../common/scss/uc-home";
</style>
<style lang="scss" scoped>
@use "../common/scss/user-center";
</style>
